package com.qf.blog.filter;

import com.qf.blog.mybatis.MyBatisTool;
import com.qf.blog.mybatis.SqlSessionThreadLocal;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author zyt
 * @version 1.0
 */
@WebFilter(filterName = "SqlSessionFilter", urlPatterns = {
        "/SystemUserServlet/*","/PageServlet/*",
        "/IndexServlet/*","/UserServlet/*",
        "/static/static/discuss-publish.html",
        "/invitataionServlet/*",
        "/commentServlet/*"
})
public class SqlSessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 创建sqlsession 从封装的mybatis工具类获取
        SqlSession sqlSession = MyBatisTool.getSqlSession();
        // 把sqlsession放在 thread local中
        SqlSessionThreadLocal.set(sqlSession);
        try {
        // 放行
        chain.doFilter(request, response);
        // 提交事务
        sqlSession.commit();//调用commit操作会隐式关闭SqlSession 不用再调用关闭的方法
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
        }
    }
}
